/**
 * Copyright (c)   All Rights Reserved.
 */
package com.cargo.base.aspect;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import com.cargo.base.utils.MailSender;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.cargo.base.apo.SystemServiceLog;
import com.cargo.base.exceptions.CommonException;
import com.cargo.base.utils.JsonUtils;
import com.cargo.base.utils.PropertiesUtil;

/**
 * SystemLogAspect:监控
 * 
 * @Project Name:cargo
 * @File Name:SystemLogAspect.java
 * @Package Name:com.cargo.common.service
 * @Creator:wizard
 * @Date:2016年4月14日下午1:55:03
 */
@Aspect
@Component
public class SystemLogAspect {

	// 本地异常日志记录对象
	public static Logger logger = Logger.getLogger(SystemLogAspect.class);

	@Pointcut("execution(* com.cargo..*Service.*(..))")
	public void serviceAspect() {
	}

	@AfterThrowing(pointcut = "serviceAspect()", throwing = "e")
	public void doAfterThrowing(JoinPoint joinPoint, Throwable e) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		// 读取session中的用户
		// 获取请求ip
		String ip = request.getRemoteAddr();
		// 获取用户请求方法的参数并序列化为JSON格式字符串
		String params = "";
		if (joinPoint.getArgs() != null && joinPoint.getArgs().length > 0) {
			for (int i = 0; i < joinPoint.getArgs().length; i++) {
				params += JsonUtils.toJson(joinPoint.getArgs()[i]) + ";";
			}
		}
		try {
			/* ========控制台输出========= */
			logger.error("=====异常通知开始=====");
			StringBuffer str = new StringBuffer();
			str.append(PropertiesUtil.getValue("errorfrom"));
			str.append("\r\n");
			str.append("请求IP:" + ip);
			str.append("\r\n");
			str.append("请求路径:" + request.getRequestURL());
			str.append("\r\n");
			str.append("异常的service方法:"
					+ (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));
			str.append("\r\n");
			str.append("异常service方法的参数:" + params);
			str.append("\r\n");
			str.append("异常信息:" + e.toString());

			logger.error(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "-" + str);
			logger.error("异常详细信息", e);
			logger.error("=====异常通知结束=====");
			if (PropertiesUtil.getValue("debug").equals("true") || e instanceof CommonException) {

			} else {
			MailSender.send(PropertiesUtil.getValue("logfrom") + "Wizard捕获到异常了",
					new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "<br/>"
							+ str.toString().replaceAll("\r\n", "<br/>"));
			}
		} catch (Exception ex) {
			// 记录本地异常日志
			logger.error("==异常通知异常==");
			logger.error("异常信息:{}" + ex.getMessage());
		}
	}

	/**
	 * 获取注解中对方法的描述信息 用于service层注解
	 *
	 * @param joinPoint
	 *            切点
	 * @return 方法描述
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	public static String getServiceMthodDescription(JoinPoint joinPoint) throws Exception {
		String targetName = joinPoint.getTarget().getClass().getName();
		String methodName = joinPoint.getSignature().getName();
		Object[] arguments = joinPoint.getArgs();
		Class targetClass = Class.forName(targetName);
		Method[] methods = targetClass.getMethods();
		String description = "";
		SystemServiceLog anno = null;
		for (Method method : methods) {
			if (method.getName().equals(methodName)) {
				Class[] clazzs = method.getParameterTypes();
				if (clazzs.length == arguments.length) {
					anno = method.getAnnotation(SystemServiceLog.class);
					if (anno != null) {
						description = method.getAnnotation(SystemServiceLog.class).description();
					}
					break;
				}
			}
		}
		return description;
	}

}
